package com.liyunc.demo.service.impl;

import com.liyunc.demo.model.entity.GoodsEntity;
import com.liyunc.demo.utils.OrderRecord;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author liyuncong
 * @version 1.0
 * @file CacheServiceImpl
 * @brief CacheServiceImpl
 * @details CacheServiceImpl
 * @date 2022/4/17
 *
 * 用hash模拟redis缓存
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022/4/17                   liyuncong          Created
 */
@Service
public class CacheServiceImpl {

    //商品缓存
    public Map<Long, GoodsEntity> stockMap;
    //订单缓存
    public LinkedBlockingQueue<OrderRecord> orderRecords;
    //用户下订单记录
    public LinkedHashSet<String> userOrderRecords;

    @PostConstruct
    private void init() {
        stockMap = new ConcurrentHashMap<>();
        orderRecords = new LinkedBlockingQueue<>();
        userOrderRecords = new LinkedHashSet<>();
    }

    public List<GoodsEntity> findAll() {
        HashMap<Long, GoodsEntity> goods = (HashMap<Long, GoodsEntity>) stockMap;
        Set<Map.Entry<Long, GoodsEntity>> entrySet = goods.entrySet();
        Iterator<Map.Entry<Long, GoodsEntity>> iterator = entrySet.iterator();
        List<GoodsEntity> list = new ArrayList<>();
        while (iterator.hasNext()) {
            list.add(iterator.next().getValue());
        }
        goods.clear();
        return list;
    }

    public GoodsEntity findOne(Long id) {
        HashMap<Long, GoodsEntity> goods = (HashMap<Long, GoodsEntity>) stockMap;
        GoodsEntity entity = goods.get(id);
        goods.clear();
        return entity;
    }

    public void delete(Long id) {
        stockMap.remove(id);
    }
}
